<template>
  <div class="mod-prod-sku-tag">
    <el-form-item label="商品规格">
      <el-button size="mini" @click="shopTagInput()">添加规格</el-button>
      <div v-for="(tag, tagIndex) in skuTags" :key="tagIndex">
        <span>{{ tag.name }}</span>
        <el-button class="button-new-tag" type="text" icon="el-icon-delete" @click="removeTag(tagIndex)">删除</el-button>
        <br>
        <el-tag
          v-for="(tagItem, tagItemIndex) in tag.selectValues"
          :key="tagItem"
          closable
          :disable-transitions="false"
          @close="handleTagClose(tagIndex, tagItemIndex)"
        >
          {{ tagItem }}
        </el-tag>
        <el-input
          v-if="tagItemInputs[tagIndex] && tagItemInputs[tagIndex].visible"
          :ref="`saveTagInput${tagIndex}`"
          v-model="tagItemInputs[tagIndex].value"
          class="input-new-tag"
          size="small"
          @keyup.enter.native="handleInputConfirm(tagIndex)"
          @blur="handleInputConfirm(tagIndex)"
        />
        <el-button v-else class="button-new-tag" size="small" @click="showTagInput(tagIndex)">+ 添加</el-button>
      </div>
    </el-form-item>
    <el-form-item v-show="isShowTagInput" label="规格名">
      <el-col :span="8">
        <el-select v-model="addTagInput.id" filterable allow-create default-first-option placeholder="请选择" @change="handleTagClick">
          <el-option
            v-for="item in unUseTags"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-col>
    </el-form-item>
    <el-form-item v-show="isShowTagInput" label="规格值">
      <el-col :span="8">
        <el-select v-model="addTagInput.selectValues" multiple filterable allow-create default-first-option placeholder="请选择">
          <el-option
            v-for="(item,index) in dbTagValues"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-col>
    </el-form-item>
    <el-form-item>
      <el-button v-show="isShowTagInput" size="mini" type="primary" @click="addTag()">确定</el-button>
      <el-button v-show="isShowTagInput" size="mini" @click="hideTagInput()">取消</el-button>
    </el-form-item>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: [],
      isShowTagInput: false,
      addTagInput: {
        id: undefined,
        name: '',
        selectValues: []
      },
      tagItemInputs: [],
      // sku的标记
      // tags: [],
      // 根据选定的规格所查询出来的规格值
      dbTagValues: [],
      specs: [], // 使用的规格
      initing: false
    }
  },
  props: {
    propList: { // 系统已有的属性列表
      default: () => [],
      type: Array
    },
      skuTags: {
          default: () => [],
          type: Array
      }
  },
  computed: {
    // 未使用的规格, 通过计算属性计算
    unUseTags() {
      const res = []
      for (let i = 0; i < this.propList.length; i++) {
        const dbTag = this.propList[i]
        const specIndex = this.skuTags.findIndex(tag => tag.name === dbTag.name)
        if (specIndex === -1) {
          res.push(dbTag)
        }
      }
      return res
    },
    defalutSku() {
      return this.$store.state.prod.defalutSku
    }
  },
  watch: {
    skuTags: {
      handler(val, oldVal) {
        if (this.initing) {
          this.initing = false
          return
        }
        let skuList = []
        let tempSkuList = []
        val.forEach(tag => {
          if (skuList.length === 0) {
            tag.selectValues.forEach(tagItem => {
              const sku = Object.assign({}, this.defalutSku)
                //`${tag.tagName}:${tagItem}`
              sku.properties = {name:tag.tagName,value:tagItem} // 销售属性组合字符串
              skuList.push(sku)
            })
          } else {
            tempSkuList = []
            tag.selectValues.forEach(tagItem => {
              skuList.forEach(sku => {
                const newSku = Object.assign({}, sku)
                newSku.properties = `${sku.properties};${tag.tagName}:${tagItem}`
                tempSkuList.push(newSku)
              })
            })
            skuList = tempSkuList
          }
        })
        if (!skuList.length) {
          skuList.push(Object.assign({}, this.defalutSku))
        }
        // debugger
        this.$emit('change', skuList)
      },
      deep: true
    }
  },
  created: function() {
    this.skuTags.forEach(tag=>{
        this.tagItemInputs.push({ visible: false, value: '' })
    })
  },
  methods: {
    //    init(skuList) {
    //      this.value = skuList
    //      if (!skuList || !skuList.length) {
    //        this.$emit('change', [Object.assign({}, this.defalutSku)])
    //        return
    //      }
    //      this.initing = true
    //      const skuTags = []
    //      for (let i = 0; i < skuList.length; i++) {
    //        const sku = skuList[i]
    //        if (!sku.properties) break
    //        const propertiesArray = sku.properties.split(';')
    //        for (const j in propertiesArray) {
    //          const cnProperties = propertiesArray[j].split(':')
    //          if (!skuTags[j]) {
    //            skuTags[j] = {
    //              tagName: cnProperties[0],
    //              tagItems: []
    //            }
    //            this.tagItemInputs.push({ visible: false, value: '' })
    //          }
    //          const tagItemNameIndex = skuTags[j].tagItems.findIndex((tagItemName) => tagItemName === cnProperties[1])
    //          if (tagItemNameIndex === -1) {
    //            skuTags[j].tagItems.push(cnProperties[1])
    //          }
    //        }
    //      }
    //      this.skuTags = skuTags
    //      this.initing = false
    //    },
    // 显示规格名、规格值输入框
    shopTagInput() {
      this.isShowTagInput = true
    },
    // 隐藏规格名、规格值输入框
    hideTagInput() {
      this.isShowTagInput = false
      this.cleanTagInput()
    },
    addTag() {
      const selectValues = this.addTagInput.selectValues
      if (!this.addTagInput.id) {
        this.$message.error('请选择规格名')
        return
      }
      if (!selectValues.length) {
        this.$message.error('请选择规格值')
        return
      }
      this.isShowTagInput = false
      const tagItems = []
      for (let i = 0; i < selectValues.length; i++) {
        const element = selectValues[i]
        tagItems.push(element)
      }
      this.tagItemInputs.push({ visible: false, value: '' })
      this.$emit('addTag',this.addTagInput);
      this.cleanTagInput()
    },
    // 清除规格值输入框内容
    cleanTagInput() {
      this.addTagInput = {
        name: '',
        selectValues: []
      }
    },
    // 规格名输入框，选中规格事件
    handleTagClick() {
      const _this = this
      this.addTagInput.selectValues = []
      this.propList.forEach(function(item, index) {
        if (item.id === _this.addTagInput.id) {
          _this.addTagInput.name = item.name
          _this.dbTagValues = item.valueList
        }
      })
    },
    // 关闭标签
    handleTagClose(tagIndex, tagItemIndex) {
        if(this.skuTags[tagIndex].selectValues.length==1){
            this.$confirm('当前属性只有一个值了，该操作将删除属性【'+this.skuTags[tagIndex].name+'】?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$emit('handleTagClose',tagIndex, tagItemIndex)
            })
        }else{
            this.$confirm('确认删除该属性值【'+this.skuTags[tagIndex].selectValues[tagItemIndex]+'】?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$emit('handleTagClose',tagIndex, tagItemIndex)
            })
        }
    },
    // 标签输入框确定时调用
    handleInputConfirm(tagIndex) {
      const tagItem = this.tagItemInputs[tagIndex].value
      if (tagItem) {
          this.$emit('addPropValue',tagIndex,tagItem);
        // this.$store.commit('prod/addSkuTagItem', { tagIndex, tagItem })
      }
      this.tagItemInputs[tagIndex].visible = false
      this.tagItemInputs[tagIndex].value = ''
    },
    // 显示标签输入框
    showTagInput(tagIndex) {
      this.tagItemInputs.push({ visible: false, value: '' })
      this.tagItemInputs[tagIndex].visible = true
      this.$nextTick(() => {
        this.$refs[`saveTagInput${tagIndex}`][0].$refs.input.focus()
      })
    },
    removeTag(tagIndex) {
        this.$confirm('确认删除该属性【'+this.skuTags[tagIndex].name+'】?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            this.$emit('removeTag',tagIndex)
        })
    }
  }
}
</script>

<style lang="scss">

  .mod-prod-sku-tag{
    .el-tag + .el-tag {
      margin-left: 10px;
    }
    .button-new-tag {
      margin-left: 10px;
      height: 32px;
      line-height: 30px;
      padding-top: 0;
      padding-bottom: 0;
    }
    .input-new-tag {
      width: 90px;
      margin-left: 10px;
      vertical-align: bottom;
    }
  }
</style>
